<template>
  <div class="mod-home" v-if="false">
		<el-card class="zzh-user-list">
			<el-tabs v-model="activeName" type="border-card">
				<el-tab-pane label="会话队列" name="first">
					<div class="zzh-user-body">
						<div class="zzh-list-item" v-for="item in dialogueList" :key="item.from" @dblclick="dialogue(item)" v-if="item.sfconnect == 'false'">
							<el-badge is-dot class="zzh-badge-item" :hidden="item.sfread == 'true'">
								<div class="zzh-item-left">
									<img :src="item.extra.tx1" alt="头像"/>
								</div>
							</el-badge>
							<div class="zzh-item-right">
								<div class="zzh-right-row1">
									<div class="zzh-row1-left">{{item.extra.xm1}}</div>
									<div class="zzh-row1-right">{{sj( item.signTimestamp)}}</div>
								</div>
								<div class="zzh-right-row2" v-if="item.msgType == 'image'">[图片]</div>
								<div class="zzh-right-row2" v-html="item.content" v-else></div>
							</div>
						</div>
					</div>
				</el-tab-pane>
				<el-tab-pane label="我的会话" name="second">
					<div class="zzh-user-body">
						<div class="zzh-list-item" v-for="item in userList" :key="item.from" @click="selectUser(item)" v-if="item.to == loginUser.id + '.service' ">
							<el-badge is-dot class="zzh-badge-item" :hidden="item.sfread == 'true'">
								<div class="zzh-item-left">
									<img :src="item.extra.tx1" alt="头像"/>
								</div>
							</el-badge>
							<div class="zzh-item-right">
								<div class="zzh-right-row1">
									<div class="zzh-row1-left">{{item.extra.xm1}}</div>
									<div class="zzh-row1-right">{{sj( item.signTimestamp)}}</div>
								</div>
								<div class="zzh-right-row2" v-if="item.msgType == 'image'">[图片]</div>
								<div class="zzh-right-row2" v-html="item.content" v-else></div>
							</div>
						</div>
					</div>
				</el-tab-pane>
			</el-tabs>
		</el-card>
		<el-card class="zzh-chat">
			<div slot="header" class="zzh-chat-head">
				<span>{{currentUser.extra.xm1||'对话框'}}</span>
			</div>
			<div class="zzh-chat-body">
				<div class="zzh-body-content" ref="scrollContent">
					<div v-for="(item,index) in chatList" :key="index">
						<div v-if="item.signTimestamp" class="zzh-content-time"><el-tag type="info">{{sj(item.signTimestamp)}}</el-tag></div>
						<div :class="(item.from == loginUser.id +'.service') ? 'zzh-content-item-right' : 'zzh-content-item-left'">
							<div class="zzh-item-avatar">
								<img :src="item.extra.tx1"/>
							</div>
							<div class="zzh-item-content">
								<div class="zzh-content-username" v-if="false">{{item.extra.xm1}}</div>
								<div class="zzh-chat-text" v-if="item.msgType == 'text'">
									<span v-html="item.content"></span>
									<div class="nav"></div>
								</div>
								<div class="zzh-chat-image" v-else-if="item.msgType == 'image'">
									<img :src="item.content" :preview="item.from"/>
								</div>
							</div>
						</div>
					</div>
				</div>
				<div v-bind:class="[isActive ? 'zzh-body-activeClass' : '', 'zzh-body-bottom']">
					<div class="zzh-bottom-buttons">
						<el-popover
							placement="top-start"
							trigger="click"
							width="476">
							<el-row>
							  <el-col class="zzh-box-emoji" v-for="(item, index) in emojiList" :key="index">
								<img :src="emojiAddr + item.name + '.png'" @click="selectEmoji(item)"/>
							  </el-col>
							</el-row>
							<i class="zzh-buttons-item" slot="reference"><icon-svg name="ziyuan"></icon-svg></i>
						</el-popover>
						<el-upload
							:action="updateUrl"
							:show-file-list="false"
							:on-success="handlePicUrlSuccess"
							:before-upload="beforePicUrlUpload">
							<i class="el-icon-picture zzh-buttons-item"></i>
						</el-upload>
					</div>
					<div class="zzh-bottom-input">
						<zzh-chat-box 
							ref="chatbox"
							@submit="sendMsg()"
							@focus="isActive = !isActive"
							@blur="isActive = !isActive">
						</zzh-chat-box>
					</div>
					<div class="zzh-buttom-control">
						<el-button class="zzh-control-send" type="info" plain size="mini" @click="linkmomo()">@慧慧</el-button>
						<el-button class="zzh-control-send" type="info" plain size="mini" @click="sendMsg()">发送(S)</el-button>
					</div>
				</div>
			</div>
		</el-card>
  </div>
</template>

<script>
	import db from '@/utils/indexedDB'
	import onPaste from '@/utils/paste'
	import { formatDate,clone,getCursorPosition,setCursorPosition} from '@/utils'
	import ZzhChatBox from '@/components/zzh-chat-box'
	export default {
		data () {
		  return {
				tiows:{},
				userList:[],
				dialogueList:[],
				currentUser:{
					chatType: "",
					msgType: "",
					from: "",
					to: "",
					identity: "",
					content: "",
					sfconnect: "",
					signTimestamp:"",
					sfread:"false",
					extra:{
						tx1: "",
						tx2: "",
						xm1: "",
						xm2: ""
					}
				},
				loginUser:{
					id:"123456",
					name:"客服1",
					avatar:"http://inspiration.oss-cn-hongkong.aliyuncs.com/assets/logo.png"
				},
				chatList:[],
				sendTime:'',
				activeName:'first',
				editor:null,
				cursorPosition :0,
				isActive:false,
				emojiList:[],
				face:null,
				emojiAddr:'/static/img/ChatBox/emotion/',
				updateUrl: '',
		  }
		},
		components: {
			ZzhChatBox
		},
		activated () {
/* 			var that = this;
			this.updateUrl = this.$http.adornUrl(`/sys/oss/upload?token=${this.$cookie.get('token')}`)
			that.loginUser.id = this.$store.state.user.id
			that.loginUser.name = this.$store.state.user.name
			db.initDB();
			db.get({tablename:"dialogue"}).then(ret => {
				that.dialogueList = ret
			})
			db.get({tablename:"users"}).then(ret => {
				that.userList = ret
			})
			that.initIM();
			this.getEmoji(); */
		},
		mounted () {
			this.editor = this.$refs['editor']
		},
		methods: {
			//IM初始化
			initIM () {
				var that = this;
				that.tiows = new that.$tio.ws({
					paramStr: {
						appKey:"zzhwhh519517",
						nonce:"14314",
						signTimestamp:"1408710653000",
						signature:"30be0bbca9c9b2e27578701e9fda2358a814c88f",
						userId:that.loginUser.id,
						groups:"",
						identity:"service"
					},
					handler: {
						onopen : function (event, ws) {},
						onclose : function (event, ws) {},
						onerror : function (event, ws) {},
						ping : function (ws) {
							ws.send(JSON.stringify({chatType:"heartbeat"}))
						},
						onmessage : function (data, ws) {
							//console.log("接收消息",data)
							if(data.code==202){
								that.handle202(data.data);
							}else if(data.code==203){
								that.handle203(data.data);
							}else if(data.code==204){
								that.handle204(data.data);
							}
						}
					}
				})
				that.tiows.connect();
			},
			//处理用户请求会话
			handle204(data){
				var that = this,user = data;
				user.extra = JSON.parse(user.extra)
				user.content = that.hangleMsg({msg : user.content, msgType : user.msgType});
				db.insert("message",user).then(ret =>{})
				db.get({tablename:"dialogue", keyValue:user.from}).then(ret => {
					if(!user.signTimestamp){
						user.signTimestamp = new Date().getTime();
					}
					if(ret.length == 0){
						db.insert("dialogue",user).then(ret =>{
							db.get({tablename:"dialogue"}).then(ret => {
								that.dialogueList = ret
							})
						})
					}else{
						db.update("dialogue",user).then(ret =>{
							db.get({tablename:"dialogue"}).then(ret => {
								that.dialogueList = ret
							})
						})
					}
				})
			},
			//处理客服应答消息
			handle203(data){
				var that = this;
				db.get({tablename:"dialogue", keyValue:data.to}).then(ret => {
					if(ret.length == 1){
						var user = ret[0];
						user.sfconnect = 'true'
						user.to = data.from
						db.update("dialogue",user).then(ret =>{
							db.get({tablename:"dialogue"}).then(ret => {
								that.dialogueList = ret
								if( that.loginUser.id + ".service" == data.from ){
									that.selectUser(user);
									that.activeName = 'second';
								}else{
									if(data.to == that.currentUser.from){
										that.currentUser = {
											chatType: "",
											msgType: "",
											from: "",
											to: "",
											identity: "",
											content: "",
											sfconnect: "",
											signTimestamp:"",
											sfread:"false",
											extra:{
												tx1: "",
												tx2: "",
												xm1: "",
												xm2: ""
											}
										};
										that.chatList = [];
									}
									db.update("users",user).then(ret =>{
										db.get({tablename:"users"}).then(ret => {
											that.userList = ret
										})
									})
								}
							})
						})
					}
				})
			},
			//处理用户消息
			handle202(data){
				var that = this,user = data;
				user.extra = JSON.parse(user.extra)
				user.content = that.hangleMsg({msg : user.content, msgType : user.msgType});
				if(user.from == that.currentUser.from){
					user.sfread = "true"
					that.chatList.push(user)
					that.setBottom()
				}
				db.insert("message",user).then(ret =>{})
				if(!user.signTimestamp){
					user.signTimestamp = new Date().getTime();
				}
				db.update("users",user).then(ret =>{
					db.get({tablename:"users"}).then(ret => {
						that.userList = ret
					})
				})
			},
			hangleMsg({msg,msgType = "text"}){
				var that = this;
				var content = msg;
				if(msgType == "text"){
					content = content.replace(/\[.+?\]/g, function(a, b) {
						if ( that.face[a] ) {
							return '<img src="' + that.emojiAddr + that.face[a] + '" remark="' + a + '">'
						}else{
							return a
						}
					});
					content = content.replace(/@.+?\]/g, function(a, b) {
						if(a){
							var param = a.split(']')[0].split('-')
							
							return '<span remark="' + param[1] + '">' + param[0] + '</span>';
						}else{
							return "";
						}
					});
				}
				return content;
			},
			//处理用户会话请求/发送客服应答
			dialogue(item){
				var that = this;
				 var jsStr = {
				 	chatType:"service",
				 	msgType:"text",
				 	from:that.loginUser.id+".service",
				 	to:item.from,
				 	identity:"service",
				 	sfconnect:'false',
				 	content:'您好,有什么可以帮助你的吗',
				 	signTimestamp:new Date().getTime(),
				 	sfread:"false",
				 	extra:{
				 		xm1 : that.loginUser.name,
				 		xm2 : item.extra.xm1,
				 		tx1 : that.loginUser.avatar,
				 		tx2 : item.extra.tx1
				 	}
				 }
				 that.tiows.ws.send(JSON.stringify(jsStr))
			},
			//选取当前会话的对象
			selectUser(user){
				var that = this;
				if(user){
					let data = [];
					user.sfread = "true";
					that.currentUser = user
					db.get({tablename:"users", keyValue:user.from}).then(ret => {
						if(ret.length == 0){
							db.insert("users",user).then(ret =>{
								db.get({tablename:"users"}).then(ret => {
									that.userList = ret
								})
							})
						}else{
							db.update("users",user).then(ret =>{
								db.get({tablename:"users"}).then(ret => {
									that.userList = ret
								})
							})
						}
					})
					db.handleDataByCursor("message").then(request => {
						request.onsuccess = function(event) {
						  if (event.target.result) {
							if(event.target.result.value.from == user.from || event.target.result.value.to == user.from){
								data.push(event.target.result.value);
							}
						  	event.target.result.continue();
						  } else {
						    that.chatList = data
							that.setBottom()
						  }
						}
					})
				}
			},
			//获取表情信息
			getEmoji(){
				this.$http({
					url: this.emojiAddr + 'emotion.json',
					method: 'get'
				}).then(({data}) => {
					this.emojiList = data
				})
				this.$http({
					url: this.emojiAddr + 'face.json',
					method: 'get'
				}).then(({data}) => {
					this.face = data
				})
			},
			//选择表情
			selectEmoji(e){
				const src = this.emojiAddr + e.name + '.png';
				const img = "<img src='" + src + "' alt='" + e.text + "' name='emoji'/>";
				this.$refs.chatbox.insertEmoji({
					src : src,
					remark : e.text
				})
			},
			//滚到底部
			setBottom(){
				const me = this;
				setTimeout(()=>{
					this.$nextTick(() => {//一定要在this.$nextTick进行设置
						me.$refs.scrollContent.scrollTop = 100000;
					})
				},100)
			},
			//时间差计算
			sj(sj){
				if(!sj){return ''}
				var nowt = new Date().getTime();
				var a = new Date(parseInt(sj));
				var b = new Date(parseInt(nowt));
				var date1 = Date.parse(formatDate(a, 4));
				var date2 = Date.parse(formatDate(b, 4));
				var xxsj = Math.ceil((date2 - date1) / (60 * 1000))
				if (xxsj <= 1 && xxsj >= 0) {
					return "就刚才";
				} else if (xxsj <= 10 && xxsj > 1) {
					return xxsj + "分钟前";
				} else if (xxsj <= 60 && xxsj > 10) {
					return formatDate(a, 1);
				} else if (xxsj <= 1440 && xxsj > 60) {
					return formatDate(a, 1);
				} else if (xxsj <= 10080 && xxsj > 1440) {
					return formatDate(a, 2);
				} else if (xxsj > 10080) {
					return formatDate(a, 3);
				} else {
					return formatDate(a, 3);
				}
			},
			//发送消息
			sendMsg(){
				var that = this;
				var textMsg  = that.$refs.chatbox.getContent(true);
				var jsonObj = that.send({msg:textMsg});
				if(jsonObj){
					jsonObj.content = that.$refs.chatbox.getContent(false);
					db.insert("message",jsonObj).then(ret =>{
						that.chatList.push(jsonObj)
						that.setBottom()
					})
					that.$refs.chatbox.editor.innerHTML = ""
				}
			},
			// 上传图片之前的钩子
			beforePicUrlUpload (file) {
				if(this.currentUser.from && this.currentUser.extra.xm1){
					var fileType = ['image/jpeg', 'image/png', 'image/jpg']
					const isPic = fileType.join(',').indexOf(file.type) !== -1
					const isLt2M = file.size / 1024 / 1024 < 2
					if (!isPic) {
					  this.$message.error('不支持此格式的图片!')
					}
					if (!isLt2M) {
					  this.$message.error('上传图片大小不能超过 2MB!')
					}
					return isPic && isLt2M
				}else{
					return false
				}
				
			},
			// 图片上传成功时的钩子
			handlePicUrlSuccess (response) {
				var that = this;
				if (response && response.code === 0) {
					console.log(response.url)
					var jsonObj = that.send({msg : response.url, msgType : "image"});
					if(jsonObj){
						db.insert("message",jsonObj).then(ret =>{
							that.chatList.push(jsonObj)
							that.setBottom()
						})
					}
				} else {
					this.$message.error(response.msg)
				}
			},
			send({msg,msgType = "text"}){
				var that = this;
				if(msg && that.currentUser.from && that.currentUser.extra.xm1){
					var sendDate = that.sj(that.sendTime);
					if(sendDate == "就刚才"){
						sendDate = '';
					}else{
						sendDate = new Date().getTime();
					}
					that.sendTime = new Date().getTime();
					var jsonObj = {
							chatType:"service",
							msgType:msgType,
							from:that.loginUser.id+".service",
							to:that.currentUser.from,
							identity:"service",
							sfconnect:that.currentUser.sfconnect,
							content:msg,
							signTimestamp:sendDate,
							sfread:"false",
							extra:{
								xm1 : that.loginUser.name,
								xm2 : that.currentUser.extra.xm1,
								tx1 : that.loginUser.avatar,
								tx2 : that.currentUser.extra.tx1
							}
					}
					var jsonStr = JSON.stringify(jsonObj)
					that.tiows.ws.send(jsonStr)
					return jsonObj;
				}
			},
			//得到光标位置
			getCursor () {
				this.cursorPosition = getCursorPosition(this.editor)
			},
			//输入框粘贴事件
			async onPaste (e) {
				console.log("粘贴事件")
				const result = await onPaste(e)
				const imgRegx = /^data:image\/png;base64,/
				if (imgRegx.test(result)) {
					const sel = window.getSelection()
					if (sel && sel.rangeCount === 1 && sel.isCollapsed) {
						const range = sel.getRangeAt(0)
						const img = new Image()
						img.src = result
						range.insertNode(img)
						range.collapse(false)
						sel.removeAllRanges()
						sel.addRange(range)
					}
					//document.execCommand('insertImage', false, result)
				} else {
					document.execCommand('insertText', false, result)
				}
			},
			//发送文本消息
			linkmomo(){
				this.$refs.chatbox.insertBlock({
					text : '@慧慧',
					color : 'red',
					remark : "zzh"
				})
			},
		}
  }
</script>

<style lang="scss">
	.mod-home {
		line-height: 1.5;
			display: -webkit-flex;
			display: flex;
	}
	.zzh-box-emoji{
		width: 30px;
		height: 30px;
		padding: 2px;
		img{
			width:100%;
			height:100%;
		}
	}
	.zzh-box-emoji:hover{
		background:#E7E7E7;
	}
	.zzh-user-list{
		width: 260px;
		.el-card__body{
			padding:0;
		}
		img[remark]{
			width: 18px;
			height: 18px;
		}
		input{
			cursor: default;
			background: transparent;
			border: 0px;
		}
	}
	.el-tabs--border-card{
		border: 0px;
		box-shadow:0px;
		-webkit-box-shadow: 0 0px 0px 0 rgba(0,0,0,.12), 0 0 0px 0 rgba(0,0,0,.04);
		box-shadow: 0 0px 0px 0 rgba(0,0,0,.12), 0 0 0px 0 rgba(0,0,0,.04);
	}
	.el-tabs__item {
		padding: 21px 20px;
		height: auto;
		line-height: 100%;
	}
	.zzh-user-body{
		.zzh-list-item:after{
			content: '';
			position: absolute; 
			width: 100%;
			height: 1px;
			left: 66px;
			bottom: 0; 
			background-color: #f3f2f2;
		}
		.zzh-list-item{
			display: -webkit-flex;
			display: flex;
			position:relative;
			padding:8px;
			.el-badge__content.is-fixed{
				right: -40px;
				top: 2px;
				height: 16px;
				width: 16px;
			}
			.zzh-item-left{
				position:absolute;
				width:50px;
				height:50px;
				border:1px solid #fbfbfb;
				border-radius: 4px;
				img{
					border-radius: 4px;
					width:100%;
					height:100%;
				}
			}
			.zzh-item-right{
				width:100%;
				height:50px;
				padding-left: 58px;
				font-size: 12px;
				color:#9a9a9a;
				.zzh-right-row1{
					height:25px;
					line-height: 25px;
					display: -webkit-flex;
					display: flex;
					justify-content: space-between;
					.zzh-row1-left{
						font-size: 15px;
						color:#000;
						overflow: hidden;
						text-overflow:ellipsis;
						white-space: nowrap;
					}
					.zzh-row1-right{
						white-space : nowrap 
					}
				}
				.zzh-right-row2{
					height:25px;
					line-height: 25px;
					overflow: hidden;
					text-overflow:ellipsis;
					white-space: nowrap;
				}
			}
		}
	}
	.zzh-chat{
		background:#F5F5F5;
		width: 600px;
		.el-card__body{
			padding:10px 0 0 0;
		}
		.zzh-chat-body{
			.zzh-body-content{
				height:280px;
				padding:0px 20px;
				overflow-y:auto;
				img[remark]{
					width: 24px;
					height: 24px;
					cursor: default;
					margin: 0 1px;
				}
				input{
					margin: 0 1px;
					cursor: default;
					background: transparent;
					border: 0px;
				}
				
				.zzh-content-time{
					text-align: center;
					.el-tag--medium{
						height: 20px;
						line-height: 20px;
						color: #fff;
						padding: 0px 5px;
						border: 0px;
						background: rgba(218,218,218,1);
					}
				}
				
				.zzh-chat-image{
					img{
						max-width: 150px;
						border-radius: 5px;
					}
				}
				
				.zzh-content-item-left{
					display: -webkit-flex;
					display: flex;
					margin-bottom: 10px;
					position:relative;
					width: 100%;
					.zzh-item-avatar{
						position: absolute;
						width:40px;
						height:40px;
						border:1px solid #fbfbfb;
						border-radius: 4px;
						img{
							width:100%;
							height:100%;
							border-radius: 4px;
						}
					}
					.zzh-item-content{
						padding: 0 40px 0 58px;
						.zzh-content-username{
							color:#B2B2B2;
							font-size:13px;
						}
						.zzh-chat-text{
							position:relative;
							padding: 8px;
							background: #fff;
							border-radius: 4px;
							white-space: pre-line;
							word-break: break-all;
							word-wrap: break-word;
							min-height: 24px;
							.nav {
								position          :absolute;
								top: 11px;
								left: -7px;
								overflow          :hidden;
								width             :13px;
								height            :13px;
								background        :#FFF;
								-webkit-transform :rotate(45deg);
								-moz-transform    :rotate(45deg);
								-o-transform      :rotate(45deg);
								transform         :rotate(45deg);
							}
						}
					}
				}
				
				.zzh-content-item-right{
					display: -webkit-flex;
					display: flex;
					margin-bottom: 10px;
					position: relative;
					width: 100%;
					position:relative;
					flex-direction: row-reverse;
					.zzh-item-avatar{
						position: absolute;
						right:0px;
						width:40px;
						height:40px;
						border:1px solid #fbfbfb;
						border-radius: 4px;
						img{
							width:100%;
							height:100%;
							border-radius: 4px;
						}
					}
					.zzh-item-content{
						padding: 0 58px 0 40px;
						.zzh-content-username{
							display: flex;
							display: -webkit-flex;
							flex-direction: row-reverse;
							color:#B2B2B2;
							font-size:13px;
						}
						.zzh-chat-text{
							position:relative;
							padding: 8px;
							background: rgb(158,234,106);
							border-radius: 4px;
							white-space: pre-line;
							word-break: break-all;
							word-wrap: break-word;
							min-height: 24px;
							.nav {
								position:absolute;
								top: 11px;
								right: -7px;
								overflow:hidden;
								width:13px;
								height:13px;
								background:rgb(158,234,106);
								-webkit-transform:rotate(45deg);
								-moz-transform:rotate(45deg);
								-o-transform:rotate(45deg);
								transform:rotate(45deg);
							}
						}
					}
				}
				
			}
			/*滚动条样式*/
			.zzh-body-content::-webkit-scrollbar {/*滚动条整体样式*/
				/*高宽分别对应横竖滚动条的尺寸*/
					width: 8px;
				background-color: rgba(0, 0, 0, 0);
			}
			.zzh-body-content::-webkit-scrollbar-thumb {/*滚动条里面小方块*/
			    border-radius: 4px;
			    background: #CDD2CC;
			}
			.zzh-body-content::-webkit-scrollbar-track {/*滚动条里面轨道*/
			    border-radius: 0;
			    background: rgba(0,0,0,0);
			}
			.zzh-body-activeClass{
				background:#fff;
			}
			.zzh-body-bottom {
				padding-bottom: 10px;
				.zzh-bottom-buttons{
					padding:7px 0px 0px 10px;
					border-top: 1px solid #eee;
					height: 31px;
					display: -webkit-flex;
					display: flex;
					align-items: flex-start;
					font-size: 20px;
					color:#888;
					.zzh-buttons-item{
						padding:0 8px;
					}
					.el-icon-picture{
						padding-top:2px;
						font-size:22px;
					}
				}
				.zzh-bottom-input{
					padding: 5px 20px 5px 5px;
				}
				.zzh-buttom-control{
					padding:0px 20px;
					display: -webkit-flex;
					display: flex;
					flex-direction: row-reverse;
					.el-button--info.is-plain {
						color: #909399;
						background: #f4f4f5;
						border-color: #d3d4d6;
					}
					.el-button--info.is-plain:hover{
						color: #fff;
						background: #129611;
						border-color: #129611;
					}
					.el-button--info.is-plain:active{
						color: #fff;
						background: #2cb52b;
						border-color: #2cb52b;
					}
				}
			}
		}
	}
</style>

